/*
 * @Author: LIFM0623 1944099171@qq.com
 * @Date: 2024-01-24 10:01:10
 * @LastEditors: LIFM0623 1944099171@qq.com
 * @LastEditTime: 2024-03-29 20:37:14
 * @FilePath: \scene_back_nest\src\dynamiclayer\dynamiclayer.service.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Injectable } from '@nestjs/common';
import {
  RawDynamiclayerDto,
} from './dto/create-dynamiclayer.dto';
import { UpdateDynamiclayerDto } from './dto/update-dynamiclayer.dto';
import { Dynamiclayer } from './entities/dynamiclayer.entity';
import { Repository, In } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class DynamiclayerService {
  constructor(
    @InjectRepository(Dynamiclayer)
    private readonly dynamiclayerRepository: Repository<Dynamiclayer>,
  ) {}
  async create(rawDynamiclayerDto: RawDynamiclayerDto) {
    const dynamiclayer = this.dynamiclayerRepository.create(rawDynamiclayerDto);
    const insertRes = await this.dynamiclayerRepository.insert(dynamiclayer);
    return insertRes.raw;
  }

  async createForScript(rawDynamiclayerDto: RawDynamiclayerDto) {
    const dynamiclayer = this.dynamiclayerRepository.create(rawDynamiclayerDto);
    const insertRes = await this.dynamiclayerRepository.insert(dynamiclayer);
    return insertRes.raw[0].id;
  }

  async findAll(): Promise<Dynamiclayer[]> {
    return this.dynamiclayerRepository.find();
  }

  async findByIds(ids: string[]): Promise<Dynamiclayer[]> {
    return this.dynamiclayerRepository.find({
      where: {
        id: In(ids), // 使用TypeORM的In操作符
      },
    });
  }

  async findOne(id: string): Promise<Dynamiclayer> {
    return this.dynamiclayerRepository.findOne({ where: { id: id } });
  }

  async update(
    id: string,
    updateDynamiclayerDto: UpdateDynamiclayerDto,
  ) {
    // 查找旧的用户实体
    const oldDynamicLayer = await this.dynamiclayerRepository.findOne({
      where: { id: id },
    });
    if (!oldDynamicLayer) {
      return '动态绘制线条目不存在';
    }
    const updatedDynamicLayer = this.dynamiclayerRepository.merge(
      oldDynamicLayer,
      updateDynamiclayerDto,
    );
    await this.dynamiclayerRepository.save(updatedDynamicLayer);
    return '修改动态绘制线条目属性成功!';
  }

  async remove(id: string) {
    try {
      const result = await this.dynamiclayerRepository.delete({ id: id });

      if (result.affected && result.affected > 0) {
        return `成功删除 ${result.affected} 条记录`;
      } else {
        return `未找到匹配的记录，没有进行删除操作`;
      }
    } catch (err) {
      console.error('删除记录失败', err);
      throw '删除记录失败';
    }
  }
}
